package servlet;

import bean.HouseInfo;
import bean.HouseType;
import utils.DBUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/add")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        1. 编写sql语句 使用JSP显示
        String sql = "select * from house_type ";
//        2. 将sql语句 传给工具类
        ResultSet re = DBUtil.query(sql);
//        3. 设置一个集合，遍历结果集，封装成对象 再将对象添加到集合中
        ArrayList<HouseType> list = new ArrayList<>();
        try {
            while (re.next()){
                int id = re.getInt(1);
                String type = re.getString(2);
                HouseType hous = new HouseType(id, type);
                list.add(hous);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
//        4. 把集合添加request请求域中
        request.setAttribute("list",list);
//        5. 将请求转发给jSP
        request.getRequestDispatcher("/WEB-INF/add.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1 处理乱码
        request.setCharacterEncoding("utf-8");
        // 2 接收表单数据
        String leaseMode = request.getParameter("leaseMode");
        String rent = request.getParameter("rent");
        String contacts = request.getParameter("contacts");
        String depositMethod = request.getParameter("depositMethod");
        String type = request.getParameter("type");
        String address = request.getParameter("address");
        // 3 编写sql
        String sql = "insert into house_info values (?,?,?,?,?,?,?)";
        // 4 调用工具类执行SQL，得到影响的行数
        int i = DBUtil.update(sql, null, leaseMode, rent, contacts, depositMethod, type, address);
        // 5 根据影响的行数，做判断提示
        if (i>0){
            // 使用响应的重定向可以直接刷新列表
            response.sendRedirect("/list");
        }else{
            // 在request域中添加失败的提示信息
            request.setAttribute("msg","添加失败");
            // 5 将请求转发给jsp
            request.getRequestDispatcher("/WEB-INF/msg.jsp").forward(request,response);
    }
}
}
